package com.syuchen.server.http.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class HttpBioServer {

    private ServerSocket serverSocket;
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 初始化线程池
     */
    private void initThreadPool() {
        int corePoolSize = 50;//核心线程数
        int maximumPoolSize = 200;//最大大小，当线程池满时执行拒绝策略
        long keepAliveTime = 100L;//空闲的非核心线程最大存活时间
        TimeUnit unit = TimeUnit.SECONDS;//单位，秒
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);//等待队列，核心线程全部繁忙时进入等待队列，队满时则创建新的线程
        ThreadFactory threadFactory = Executors.defaultThreadFactory();//线程工厂,默认的
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();//拒绝策略

        this.threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    /**
     * 开启端口监听
     * @param port 端口
     */
    public void listen(int port){
        try{
            initThreadPool();
            serverSocket = new ServerSocket(port);
            while(true) {
                this.acceptTcp();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 接收客户端连接请求
     */
    private void acceptTcp() throws IOException {
        //接收客户端的连接
        Socket clientSocket = serverSocket.accept();
        clientSocket.setSoTimeout(3600*1000);
        //每个客户端对应一个线程
        BioThread bio = new BioThread(clientSocket);
        //在线程池中去执行
        threadPoolExecutor.execute(bio);
    }
}
